//
//  ByViewIndexCarousel.m
//  itboye_shop_ios
//
//  Created by pro on 17/2/7.
//  Copyright © 2017年 com.itboye. All rights reserved.
//

#import "ByViewIndexCarousel.h"

// 分页视图的圈圈颜色定义
#define KPageCurrentTintColor       [UIColor redColor]
#define KPageNormalTintColor        [UIColor colorWithWhite:0.9 alpha:0.6]

// 当轮播数组为空时，默认添加一个该字段，展示“无数据”图片
#define KNoCarouselURLString        @"default"

// 默认的轮播图片
#define KDefaultCarouselImage       [UIImage imageNamed:@"default1-2"]
#define KNoAvailableCarouselImage   [UIImage imageNamed:@"default1-2"]

// 图片视图的BaseTag
#define KImageViewBaseTag 10

@interface ByViewIndexCarousel () <UIScrollViewDelegate>
{
    // data
    NSInteger   _carouselAmount;    // 轮播数
    CGFloat     _duration;          // 轮播时间间隔
}

// view
@property (nonatomic, strong) UIScrollView              *scroll;        // 滑动视图
@property (nonatomic, strong) UIPageControl             *pageControl;   // 分页视图
@property (nonatomic, strong) UIActivityIndicatorView   *activity;      // 等待视图

// 定时器
@property (nonatomic, strong) NSTimer                   *timer;

@end

@implementation ByViewIndexCarousel

- (void)dealloc {
    [self.timer invalidate];
    self.timer = nil;
}

// 初始化frame和轮播时间间隔
- (instancetype)initWithFrame:(CGRect)frame
                timerDuration:(CGFloat)duration {
    
    if (self = [super initWithFrame:frame]) {
        
        _duration = duration;
        
        // 未获得轮播视图时，先显示菊花转动，用作等待效果
        [self.activity startAnimating];
        
        // 开启定时器
        self.timer = [NSTimer scheduledTimerWithTimeInterval:_duration target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
    return self;
}
// 设置轮播图片
- (void)setImageModels:(NSArray *)imageModels {
    
    // 关闭等待效果
    [self.activity stopAnimating];
    
    // 如果没轮播图，则设置一张默认的图片，且不轮播
    if (imageModels == nil || imageModels.count == 0) {
        
        ByModelIndexCarsouel *NCModel = [[ByModelIndexCarsouel alloc] init];
        NCModel.imageURL = KNoCarouselURLString;
        imageModels = @[NCModel];
    }
    
    // 给视图的图片URL字符串数组赋值
    NSMutableArray *temp = [NSMutableArray array];
    temp = [imageModels mutableCopy];
    [temp addObject:imageModels[0]];
    [temp insertObject:imageModels[imageModels.count - 1] atIndex:0];
    
    // 设置好轮播数组
    _imageModels = [temp copy];
    
    // 设置轮播数量
    _carouselAmount = _imageModels.count - 2;
    
    // 如果只有一张图片，则不轮播
    if (_carouselAmount == 1) {
        [self.timer invalidate];
        self.timer = nil;
        [self.scroll setScrollEnabled:NO];
        [self.pageControl setHidden:YES];
    } else {
        [self.pageControl setHidden:NO];
        [self.pageControl setNumberOfPages:_carouselAmount];
    }
    
    // 给轮播图片视图设置从网上获取的图片
    for (int tag = KImageViewBaseTag; tag < KImageViewBaseTag + _carouselAmount + 2; tag ++) {
        
        UIImageView *imageView = (UIImageView *)[self.scroll viewWithTag:tag];
        
        ByModelIndexCarsouel *CModel = _imageModels[tag - KImageViewBaseTag];
        NSString *URLString = CModel.imageURL;
        // 如果图片数组为空，则需要显示一张无数据的图片（注意，和默认图片是不同的）
        if ([URLString isEqualToString:KNoCarouselURLString]) {
            imageView.image = KNoAvailableCarouselImage;
        } else {
            [imageView setImageWithURL:[NSURL URLWithString:URLString] placeholderImage:KDefaultCarouselImage completed:nil];
        }
    }
    
}


#pragma mark - 视图懒加载
// 等待视图
- (UIActivityIndicatorView *)activity {
    
    if (!_activity) {
        _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _activity.center = CGPointMake(self.width / 2, self.height / 2);
        _activity.hidesWhenStopped = YES;
        [self addSubview:_activity];
    }
    return _activity;
}
// 分页视图
- (UIPageControl *)pageControl {
    
    if (!_pageControl) {
        _pageControl = [[UIPageControl alloc] initWithFrame:CGRectZero];
        _pageControl.backgroundColor = [UIColor clearColor];
        _pageControl.currentPageIndicatorTintColor = KPageCurrentTintColor;
        _pageControl.pageIndicatorTintColor = KPageNormalTintColor;
        _pageControl.hidden = YES;
        _pageControl.bottom = self.height - 10;
        _pageControl.x = self.width / 2;
        [self addSubview:_pageControl];
    }
    return _pageControl;
}
// 滑动视图
- (UIScrollView *)scroll {
    
    if (!_scroll && _carouselAmount != 0) {
        _scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height)];
        _scroll.contentSize = CGSizeMake(_scroll.width * (_carouselAmount + 2), 0);
        _scroll.pagingEnabled = YES;
        _scroll.showsHorizontalScrollIndicator = NO;
        _scroll.delegate = self;
        
        // _carouselAmount 张主图，在最左和最右各添加一张用作轮播
        for (int i = 0; i < _carouselAmount + 2; i ++) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i * _scroll.width, 0, _scroll.width, _scroll.height)];
            imageView.image = KDefaultCarouselImage;        // 先展示默认的图片
            imageView.tag = KImageViewBaseTag + i;
            [_scroll addSubview:imageView];
            imageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickViewAtIndex:)];
            [imageView addGestureRecognizer:tap];
        }
        
        // 默认先显示第一张图片
        _scroll.contentOffset = CGPointMake(_scroll.width, 0);
        
        // 把滑动视图作为最底部的视图
        [self insertSubview:_scroll atIndex:0];
    }
    
    return _scroll;
}



#pragma mark - 滑动视图代理
// 滑动视图已经停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    //如果已经滑动到最后一张，则跳到第二张
    if (self.scroll.contentOffset.x == (_carouselAmount + 1) * self.scroll.width) {
        self.scroll.contentOffset = CGPointMake(self.scroll.width, 0);
    }
    //如果滑动到到第一张，则跳到倒数第二张
    else if (self.scroll.contentOffset.x == 0) {
        self.scroll.contentOffset = CGPointMake(_carouselAmount * self.scroll.width, 0);
    }
    
    // 设置分页视图的当前页数显示
    NSInteger curPage = self.scroll.contentOffset.x / self.scroll.width - 1;
    self.pageControl.currentPage = curPage;
}


#pragma mark - 定时器方法
// 定时器方法
- (void)timerAction:(NSTimer *)timer {
    
    // 如果还未创建则跳过定时器方法
    if (!self.scroll) {
        return;
    }
    
    // 跳转到下一页
    [UIView animateWithDuration:0.5 animations:^{
        self.scroll.contentOffset = CGPointMake(self.scroll.contentOffset.x + self.scroll.width, 0);
    }];
    // 如果已经滑动到最后一张，则跳到第二张
    if (self.scroll.contentOffset.x == (_carouselAmount + 1) * self.scroll.width) {
        self.scroll.contentOffset = CGPointMake(self.scroll.width, 0);
    }
    // 如果滑动到到第一张，则跳到倒数第二张
    if (self.scroll.contentOffset.x == 0) {
        self.scroll.contentOffset = CGPointMake(_carouselAmount * self.scroll.width, 0);
    }
    
    // 设置分页视图的当前页数显示
    NSInteger curPage = self.scroll.contentOffset.x / self.scroll.width - 1;
    self.pageControl.currentPage = curPage;
}

#pragma mark - 点击事件
// 点击轮播的内容视图
- (void)clickViewAtIndex:(UITapGestureRecognizer *)tap {
    
    NSInteger tag = tap.view.tag;
    NSInteger tapIndex = tag - (KImageViewBaseTag + 1);
    
    [ByCoreToolAlert showOnlyText:[NSString stringWithFormat:@"您点击了第%li个视图!", tapIndex]];
}

@end
